package org.basis.enhance.async.init.listener;

import org.basis.enhance.async.init.executor.AsyncTaskExecutor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.NonNull;

/**
 * <p>
 * 异步初始化执行listener
 * </p>
 *
 * @author wenpan 2023/06/11 17:09
 */
public class AsyncTaskExecutionListener implements ApplicationListener<ContextRefreshedEvent>, PriorityOrdered, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
        // 必须是同个容器才ensure，避免多个容器相互干扰
        if (applicationContext.equals(event.getApplicationContext())) {
            AsyncTaskExecutor.ensureAsyncTasksFinish();
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
